package yagwl.server.fnd;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import yagwl.client.model.MasterDetailDTO;
import yagwl.client.model.fnd.FndRpcService;
import yagwl.client.model.fnd.RpcStatus;
import yagwl.service.fnd.flex.FlexEntityEntity;
import yagwl.service.fnd.flex.FlexEntityService;
import yagwl.service.fnd.flex.FlexEntityServiceImpl;
import yagwl.service.util.svc.BaseException;
import yagwl.service.util.svc.Context;

@SuppressWarnings("serial")
public class FndRpcServiceImpl extends RemoteServiceServlet implements FndRpcService {

  private static final Logger log = Logger.getLogger(FndRpcServiceImpl.class
      .getName());
  private FlexEntityService flexEntitySvc = FlexEntityServiceImpl.getInstance();

  @Override
  public List<MasterDetailDTO> getFlexEntities() {
    List<FlexEntityEntity> list = flexEntitySvc.getFlexEntities();
    List<MasterDetailDTO> dtoList = new ArrayList<MasterDetailDTO>();
    for (FlexEntityEntity e : list) {
      dtoList.add(copyFlexEntity(e));
    }
    return dtoList;
  }

  @Override
  public RpcStatus createFlexEntity(MasterDetailDTO entityDTO) {
    //if (!authorized())
    //  return new RpcStatus();
    FlexEntityEntity entity;
    RpcStatus stat = new RpcStatus();
    try {
      entity = flexEntitySvc.createFlexEntity(copyFlexEntity(entityDTO));
    } catch (BaseException e) {
      stat.setErrorCode(e.getErrorCode().toString());
      stat.setMessage(e.getMessage());
      return stat;
    }
    stat.setObjectId(entity.getEncryptedEntityId());
    return stat;
  }

  private FlexEntityEntity copyFlexEntity(MasterDetailDTO entityDTO) {
    FlexEntityEntity entity = new FlexEntityEntity();
    entity.setName(entityDTO.getLabel());
    return entity;
  }

  private MasterDetailDTO copyFlexEntity(FlexEntityEntity entity) {
    MasterDetailDTO dto = new MasterDetailDTO();
    dto.setLabel(entity.getName());
    return dto;
  }

  private boolean authorized() {
    Context ctx = Context.getCurrentInstance();
    return Boolean.parseBoolean(ctx.getAttributeStr("AuthorizeTransactions"));
  }

}
